<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/24
 * Time: 17:10
 */
class AsyMysql
{
    /**
     * @var string
     */
    public $dbSource = "";
    /**
     * mysql 的配置
     * @var array
     */
    public $dbConfig = array();

    public function __construct()
    {
        //new swoole_mysql;
        $this->dbSource = new Swoole\Mysql;

        $this->dbConfig = array(
            "host" => '127.0.0.1',
            "port" => 3306,
            "user" => 'super',
            "password" => 'MyPass@123',
            "database" => 'swoole',
            "charset" => 'utf8',
        );
    }

    /**
     * mysql的执行逻辑
     * @param $id
     * @param $username
     * @return bool
     */
    public function execute($id, $username)
    {
        //connect 异步连接mysql
        $this->dbSource->connect($this->dbConfig, function ($db, $result) use ($id, $username) {

            echo '此时已经connect了' . PHP_EOL;
            if ($result == false) {
                var_dump($db->connect_error);
                // todo
            }
            $sql = "UPDATE test SET `username` = '" . $username . "' WHERE `id` = " . $id;
            echo $sql . PHP_EOL;
            //query (add select update delete)
            $db->query($sql, function ($db, $result) {
                // select => result返回查询结果集
                // add update delete => result 返回bool
                if ($result == false) {
                    var_dump($db->error);
                    // todo
                } else if ($result == true) {
                    // todo
                    var_dump($db->affected_rows);
                } else {
                    print_r($result);
                }
                $db->close();
            });
        });
        return true;
    }

    public function update()
    {

    }

    public function add()
    {

    }

    public function delete()
    {

    }
}

$obj = new AsyMysql();
$flag = $obj->execute('1', 'tommy');
var_dump($flag) . PHP_EOL;
echo 'start' . PHP_EOL;